Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
Why is that for a pointer *p, p[0] is the address stored at p and p[1] is the address of p itself?

The code

int n = 25;  
int *p = &n;  
printf("%x\n %d\n %x\n", p, p[0], p[1]);

returns:

\<adress-of-p  
25  
\<adress-of-p>  

Of course I would never do this but in K&R states that

"if pa is a pointer, expressions may use it with a subscript; pa[i] is identical to *(pa+i).

so I was curious.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

This statement

printf("%x\n %d\n %x\n", p, p[0], p[1]);

invokes undefined behavior by two reasons.

The first one is that to output a pointer you should use a correct conversion specifier. The second one is that you may not dereference a pointer like this p[1] that does not point to a valid object.

Instead you could write for example

printf("%p\n %d\n %p\n", ( void * )p, p[0], ( void * )( p + 1 ) );
over 4 years ago · Santiago Trujillo Relatório

0

When you evaluate p[1] in your code, you are invoking undefined behavior so your program can do anything.

It is undefined behavior because p points at n which is just a single integer, not an array of integers. So p[0] is n, but p[1] is undefined. Basically this is an array overflow bug.

over 4 years ago · Santiago Trujillo Relatório

0

Your program has undefined behaviour, because it dereferences a pointer that doesn't point to anything.

The particular symptoms you have experienced are consistent with reading the next variable in the function

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda